package com.forlove.app.qselect.friend.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.common.widget.recyview.EndLessOnScrollListener;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.CommonEntity;
import com.forlove.app.qselect.friend.adapter.CommonSchoolAdapter;
import com.forlove.app.qselect.friend.entity.ContactsFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendListEntity;
import com.forlove.app.qselect.friend.entity.NewsFriendsStatus;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.entity.SelectEntity;
import com.forlove.app.qselect.friend.presenter.SchoolFriendPresenter;
import com.forlove.app.qselect.friend.view.SchoolFriendView;
import com.forlove.app.qselect.friend.widget.SelectSchoolTab;
import com.forlove.app.qselect.friend.widget.SelectTermView;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.SchoolDto;
import com.forlove.app.qselect.login.entity.SchoolInfoEntity;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.forlove.app.qselect.friend.ui.MineNewFriendFragment.add_new_school_friend;
import static com.forlove.app.qselect.friend.ui.MineNewFriendFragment.add_success;

/**
 * 学校好友
 * Created by yjl on 2017/11/27.
 */

public class SchoolFriendActivity extends BaseActivity<SchoolFriendPresenter> implements
        SchoolFriendView, View.OnClickListener,
        SwipeRefreshLayout.OnRefreshListener, SelectSchoolTab.SelectListener {

    @BindView(R.id.view_fade_back)
    FrameLayout view_fade_back;

    @BindView(R.id.view_select_school)
    SelectSchoolTab selectSchoolTab;

    @BindView(R.id.view_term)
    SelectTermView selectTermView;

    @BindView(R.id.list_school_view)
    RecyclerView list_school_view;

    @BindView(R.id.refresh_school_friend)
    SwipeRefreshLayout refresh_school_friend;
    private Map<Integer, SchoolInfoEntity> schoolMap = new HashMap<>(); //学校
    private List<SchoolInfoEntity> schoolInfoEntities = new ArrayList<>();
    private List<MineFriendEntity> mineFriendEntities = new ArrayList<>();
    private CommonSchoolAdapter schoolFriendAdapter;
    private UserEntity userEntity;
    private int schoolId = 674;//默认华东师范大学
    private int sex;
    private boolean isloadingMore = false;//是否正在加载更多
    private boolean isRefresh = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_shool_friend;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new SchoolFriendPresenter(this);
        }
        if (mHandler == null) {
            mHandler = new Handler();
        }
        initPage();
        loadSchoolCache();
        userEntity = UserManager.getUesrInfo(this);
        if (userEntity.school > 0) {
            schoolId = userEntity.school;
        }
        showDefaultSchool();
        requestSchoolFriend();
        initAdapter();
    }

    private void initAdapter() {
        if (schoolFriendAdapter == null) {
            schoolFriendAdapter = new CommonSchoolAdapter(this, R.layout.item_school_friends, mineFriendEntities, presenter);
        }
        list_school_view.setAdapter(schoolFriendAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        list_school_view.setLayoutManager(linearLayoutManager);
        schoolFriendAdapter.hideEmptyView();
        schoolFriendAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                MineFriendEntity mineFriendEntity = mineFriendEntities.get(position);
                if (mineFriendEntity.status == NewsFriendsStatus.CONFIRMED.getCode()) {
                    Intent intent = new Intent(SchoolFriendActivity.this, MineInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("mobile", mineFriendEntity.mobile);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else if (mineFriendEntity.status == NewsFriendsStatus.UNCONFIRM.getCode()
                        || mineFriendEntity.status == NewsFriendsStatus.UNADDED.getCode()
                        || mineFriendEntity.status == NewsFriendsStatus.WAITING.getCode()) {
                    SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                    searchFriendEntity.friendEntity = mineFriendEntity;
                    searchFriendEntity.isFriend = false;
                    searchFriendEntity.note_times = mineFriendEntity.charm;
                    Intent intent = new Intent(SchoolFriendActivity.this, SearchUserInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putSerializable("friendinfo", searchFriendEntity);
                    bundle.putString("mobile", mineFriendEntity.getAvaliableMobile());
                    intent.putExtras(bundle);
                    startActivityForResult(intent, add_new_school_friend);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        list_school_view.addOnScrollListener(new EndLessOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                //加载更多
                if (!isloadingMore && !isRefresh) {
                    isloadingMore = true;
                    schoolFriendAdapter.showFootLoading();
                    requestMoreSchoolFriend();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            schoolFriendAdapter.hideFooterView();
                            isloadingMore = false;
                        }
                    }, 6000);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == add_new_school_friend && resultCode == add_success) {
            int pos = data.getIntExtra("position", -1);
            mineFriendEntities.get(pos).status = add_new_school_friend;
            schoolFriendAdapter.notifyItemChanged(pos);

        }
    }

    private void requestMoreSchoolFriend() {
        Map param = new HashMap();
        param.put("school", schoolId);
        if (sex != 1 || sex != 2) {
            param.put("sex", "");
        } else {
            param.put("sex", sex);

        }
        presenter.loadMoreSchoolFriend(param);
    }

    private void initPage() {
        refresh_school_friend.setOnRefreshListener(this);
        refresh_school_friend.setColorSchemeResources(R.color.common_green);
        view_fade_back.setOnClickListener(this);
        selectSchoolTab.setSelectTermView(selectTermView);
        selectSchoolTab.setSelectListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    private void showDefaultSchool() {
        if (schoolId > 0) {
            for (int i = 0; i < schoolInfoEntities.size(); i++) {
                if (schoolInfoEntities.get(i).id == schoolId) {
                    selectSchoolTab.showSelectSchoolDefault(i);
                    break;
                }
            }
            selectSchoolTab.showDefaultTerm(sex);
        }
    }

    private void requestSchoolFriend() {
        Map param = new HashMap();
        param.put("school", schoolId);
        if (sex != 1 && sex != 2) {
            param.put("sex", "");
        } else {
            param.put("sex", sex);

        }
        presenter.refreshSchoolFriend(param);
    }

    private void loadSchoolCache() {
        String school = DataManager.getSchoolInfo();
        if (StringUtils.isNotEmpty(school)) {
            SchoolDto schoolDto = JSON.parseObject(school, SchoolDto.class);
            if (schoolDto != null && schoolDto.getData() != null) {
                schoolMap.clear();
                schoolMap.putAll(schoolDto.getData());
            }
        }
        schoolInfoEntities.clear();
        schoolInfoEntities.addAll(DataManager.parseSchool(this.schoolMap));
        selectSchoolTab.setSchools(schoolInfoEntities);
        presenter.loadSchoolInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_fade_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onRefresh() {
        if (!isRefresh) {
            requestSchoolFriend();
            isRefresh = true;
            isloadingMore = false;
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isRefresh = false;
                isloadingMore = false;
                refresh_school_friend.setRefreshing(false);
            }
        }, 6000);
    }

    @Override
    public void selectSchool(SelectEntity selectEntity) {
        //选择了学校
        if (selectEntity.selectPosition < schoolInfoEntities.size()) {
            SchoolInfoEntity schoolInfoEntity = schoolInfoEntities.get(selectEntity.selectPosition);
            schoolId = schoolInfoEntity.id;
//        refresh_school_friend.setRefreshing(true);
            requestSchoolFriend();
        }
    }

    @Override
    public void selectTerm(SelectEntity selectEntity) {
        //选择了条件
        sex = selectEntity.selectPosition;
//        refresh_school_friend.setRefreshing(true);
        requestSchoolFriend();
    }

    @Override
    public void showAgreeFriend(NetworkManager.ResultCode resultCode, String msg) {
        //同意请求
        if (schoolFriendAdapter.getAgreePosition() > -1) {
            int pos = schoolFriendAdapter.getAgreePosition();
            mineFriendEntities.get(pos).status = NewsFriendsStatus.CONFIRMED.getCode();
            schoolFriendAdapter.notifyItemChanged(pos);
        }
    }

    @Override
    public void showDeleteRecordView(CommonEntity commonEntity) {
        //删除记录
    }

    @Override
    public void updateContactsFriendView(ContactsFriendEntity contactsFriendEntity) {

    }

    @Override
    public void updateSchoolInfo(Map<Integer, SchoolInfoEntity> school) {
        if (school != null && !school.isEmpty()) {
            this.schoolMap.clear();
            this.schoolMap.putAll(school);
            schoolInfoEntities.clear();
            schoolInfoEntities.addAll(DataManager.parseSchool(this.schoolMap));
            selectSchoolTab.setSchools(schoolInfoEntities);
            showDefaultSchool();
        }
    }

    @Override
    public void updateSchoolFriend(List<MineFriendEntity> mineFriendEntities) {
        schoolFriendAdapter.hideFooterView();
        //查找学校好友
        isRefresh = false;
        isloadingMore = false;
        refresh_school_friend.setRefreshing(false);
        if (mineFriendEntities != null) {
            this.mineFriendEntities.clear();
            this.mineFriendEntities.addAll(mineFriendEntities);
            schoolFriendAdapter.updateDatas(mineFriendEntities);
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        isRefresh = false;
        isloadingMore = false;
        refresh_school_friend.setRefreshing(false);
    }

    @Override
    public void updateFriendListView(MineFriendListEntity mineFriendListEntity) {

    }

    @Override
    public void showScanViewData(SearchFriendEntity searchFriendEntity) {

    }
}
